package com.papers.juan.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.papers.common.annotation.Log;
import com.papers.common.annotation.RepeatSubmit;
import com.papers.common.core.controller.BaseController;
import com.papers.common.core.domain.PageQuery;
import com.papers.common.core.domain.R;
import com.papers.common.core.page.TableDataInfo;
import com.papers.common.core.validate.AddGroup;
import com.papers.common.core.validate.EditGroup;
import com.papers.common.enums.BusinessType;
import com.papers.common.excel.ExcelResult;
import com.papers.common.exception.ServiceException;
import com.papers.common.utils.poi.ExcelUtil;
import com.papers.juan.domain.bo.TJuanQuestionBo;
import com.papers.juan.domain.dto.InsertQuestion;
import com.papers.juan.domain.dto.JuanQuestionDto;
import com.papers.juan.domain.vo.KnowledgeReturnVO;
import com.papers.juan.domain.vo.QuestionVO;
import com.papers.juan.domain.vo.StatisticsByTypeVO;
import com.papers.juan.domain.vo.TJuanQuestionVo;
import com.papers.juan.listener.TJunQuestionListener;
import com.papers.juan.service.ITJuanQuestionService;
import com.papers.juan.service.ITJuanReposRelatedService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 题目
 *
 * @author papers
 * @date 2022-10-08
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/juan/juanQuestion")
public class TJuanQuestionController extends BaseController {

    private final ITJuanQuestionService iTJuanQuestionService;

    private final ITJuanReposRelatedService itJuanReposRelatedService;

    /**
     * 查询题目列表
     */
    @SaCheckPermission("juan:juanQuestion:list")
    @GetMapping("/list")
    public TableDataInfo<TJuanQuestionVo> list(TJuanQuestionBo bo, PageQuery pageQuery) {
        return iTJuanQuestionService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询题目列表
     */
    @GetMapping("/getQuestionList")
    public R getQuestionList(JuanQuestionDto dto, PageQuery pageQuery) {
        return iTJuanQuestionService.getQuestionList(dto, pageQuery);
    }

    /**
     * 查询题目列表
     */
    @GetMapping("/getQuestionListNew")
    public R getQuestionListNew(JuanQuestionDto dto, PageQuery pageQuery) {
        return iTJuanQuestionService.getQuestionListNew(dto, pageQuery);
    }

    /**
     * 导出题目列表
     */
    @SaCheckPermission("juan:juanQuestion:export")
    @Log(title = "题目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(JuanQuestionDto bo, PageQuery pageQuery, HttpServletResponse response) {
        pageQuery.setPageSize(9999);
        pageQuery.setPageNum(1);
        List<TJuanQuestionVo> list = iTJuanQuestionService.queryList(bo, pageQuery);
//        if (bo.getCourseId()==null){
//            throw  new RuntimeException("请选择题库导出");
//        }
//        List<TJuanQuestionVo> list = iTJuanQuestionService.selectQuestionList(bo);
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("题目列表为空！");
        }
        ExcelUtil.exportExcel(list, "题目", TJuanQuestionVo.class, response);
    }

    /**
     * 导出题库json
     */
    @SaCheckPermission("juan:juanQuestion:export")
    @Log(title = "题目", businessType = BusinessType.EXPORT)
    @PostMapping("/exportjson")
    public void exportJson(HttpServletRequest req, HttpServletResponse rep, @RequestBody JuanQuestionDto bo) throws UnsupportedEncodingException {
        iTJuanQuestionService.exportJson(bo, rep);
    }

    /**
     * 导入题库json
     */
    @PostMapping("/importjson")
    @SaCheckPermission("juan:juanQuestion:import")
    public R importJson(MultipartFile file) {
        if (null == file) {
            return R.fail("请选择一个文件");
        }
        boolean flag ;
        flag = iTJuanQuestionService.importJson(file);
        if (flag){
            return R.ok("导入成功");
        }else {
            return R.fail("导入失败");
        }
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "题目数据", TJuanQuestionVo.class, response);
    }

    /**
     * 导入题目
     *
     * @param file
     * @return
     */
    @PostMapping("/importQuestions")
    public R importQuestions(@RequestPart("knowledgeId") String knowledgeId,@RequestPart("couserId") String couserId,@RequestPart("file") MultipartFile file) {
        if (null == file) {
            return R.fail("请选择一个文件");
        }
        try {
            ExcelResult<TJuanQuestionVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), TJuanQuestionVo.class, new TJunQuestionListener(couserId,knowledgeId));
        } catch (ConstraintViolationException e) {
            e.printStackTrace();
            return R.fail("模板有必填项为空，请核查后再上传");
        } catch (IOException e) {
            return R.fail("导入异常，请联系管理员");
        }
        return R.ok();
    }

    /**
     * 获取题目详细信息
     *
     * @param questionId 主键
     */
    @SaCheckPermission("juan:juanQuestion:query")
    @GetMapping("/{questionId}")
    public R<TJuanQuestionVo> getInfo(@NotNull(message = "主键不能为空")
                                      @PathVariable String questionId) {
        return R.ok(iTJuanQuestionService.queryById(questionId));
    }

    /**
     * 新增题目
     */
    @SaCheckPermission("juan:juanQuestion:add")
    @Log(title = "题目", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody InsertQuestion bo) {
        return iTJuanQuestionService.addQuestion(bo);
    }

    /**
     * 修改题目
     */
    @SaCheckPermission("juan:juanQuestion:edit")
    @Log(title = "题目", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TJuanQuestionBo bo) {
        return iTJuanQuestionService.editQuestion(bo);
    }

    /**
     * 删除题目
     *
     * @param questionIds 主键串
     */
    @SaCheckPermission("juan:juanQuestion:remove")
    @Log(title = "题目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{questionIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] questionIds) {
        return toAjax(iTJuanQuestionService.deleteWithValidByIds(Arrays.asList(questionIds), true) ? 1 : 0);
    }

    /**
     * 根据ids查询题目列表
     *
     * @param ids
     * @return
     */
    @GetMapping("/getQuestionByIds")
    public R getQuestionByIds(@Param("ids") String ids) {
        return iTJuanQuestionService.getQuestionByIds(ids);
    }

    /**
     * 根据课程id查询知识点树
     * @return
     */
    @GetMapping("/getKnowledgeTreeByQuestion")
    public R getKnowledgeTreeByQuestion(@Param("department") String department) {
        return iTJuanQuestionService.getKnowledgeTreeByQuestion(department);
    }

    @GetMapping("/getKnowledgeTreeByQuestion1")
    public R getKnowledgeTreeByQuestion1(@Param("courseId")String courseId){
        return iTJuanQuestionService.getKnowledgeTreeByQuestion1(courseId);
    }

    /**
     * 根据课程id查询章节树
     *
     * @param courseId
     * @return
     */
    @GetMapping("/getChapterTreeByQuestion")
    public R getChapterTreeByQuestion(@Param("courseId") String courseId) {
        return iTJuanQuestionService.getChapterTreeByQuestion(courseId);
    }

    /**
     * 题库-按章节统计
     *
     * @param courseId
     * @return
     */
    @GetMapping("/getStatisticsByKnowledge")
    public R statisticsByKnowledge(@Param("courseId") String courseId) {
        List<KnowledgeReturnVO> returnVO = iTJuanQuestionService.statisticsByKnowledge(courseId);
        return R.ok(returnVO);
    }

    /**
     * 题库-按知识点统计
     *
     * @param courseId
     * @return
     */
    @GetMapping("/getStatisticsByPoint")
    public R getStatisticsByPoint(@Param("courseId") String courseId) {
        List<KnowledgeReturnVO> returnVO = iTJuanQuestionService.getStatisticsByPoint(courseId);
        return R.ok(returnVO);
    }

    /**
     * 题库-按题型统计
     *
     * @param courseId
     * @return
     */
    @GetMapping("/getStatisticsByType")
    public R getStatisticsByType(@Param("courseId") String courseId, @Param("type") String type) {
        List<StatisticsByTypeVO> returnVO = iTJuanQuestionService.getStatisticsByType(courseId, type);
        return R.ok(returnVO);
    }

    /**
     * 题库-按能力层次统计
     *
     * @param courseId
     * @return
     */
    @GetMapping("/getStatisticsByLevel")
    public R getStatisticsByLevel(@Param("courseId") String courseId, @Param("type") String type) {
        List<StatisticsByTypeVO> returnVO = iTJuanQuestionService.getStatisticsByLevel(courseId, type);
        return R.ok(returnVO);
    }

    /**
     * 题库-按难易度统计
     *
     * @param courseId
     * @return
     */
    @GetMapping("/getStatisticsByEasy")
    public R getStatisticsByEasy(@Param("courseId") String courseId, @Param("type") String type) {
        List<StatisticsByTypeVO> returnVO = iTJuanQuestionService.getStatisticsByEasy(courseId, type);
        return R.ok(returnVO);
    }

    /**
     * 题库-按重要性统计
     * @param courseId
     * @param type
     * @return
     */
    @GetMapping("/getStatisticsByImportance")
    public R getStatisticsByImportance(@Param("courseId") String courseId, @Param("type") String type){
        List<StatisticsByTypeVO> returnVO = iTJuanQuestionService.getStatisticsByImportance(courseId, type);
        return R.ok(returnVO);
    }
    /**
     * 题库-按相关性统计
     *
     * @param courseId
     * @return
     */
    @GetMapping("/getStatisticsByRelevance")
    public R getStatisticsByRelevance(@Param("courseId") String courseId) {
        QuestionVO returnVO = iTJuanQuestionService.getStatisticsByRelevance(courseId);
        return R.ok(returnVO);
    }

}

